package com.lungle.warmdiary.app.api;

import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.AppContext;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;

public enum OKHttpFactory {
    INSTANCE;

    private volatile OkHttpClient okHttpClient;

    private static final int TIMEOUT_READ = 60;
    private static final int TIMEOUT_CONNECTION = 60;
    private final OkHttpClient.Builder mBuilder;

    OKHttpFactory() {
        mBuilder = new OkHttpClient.Builder();
        if (AppConstant.DEBUG) {
            mBuilder.addInterceptor(HttpHelper.getHttpLoggingInterceptor());
        }
        if (AppConstant.CATCH) {
            Cache cache = new Cache(AppContext.context().getCacheDir(), 10 * 1024 * 1024);
            mBuilder.cache(cache);
        }

        mBuilder.addInterceptor(HttpHelper.getRequestHeader())
                .addInterceptor(HttpHelper.getResponseHeader())
                .retryOnConnectionFailure(true)
                .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
                .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)
                .build();

        if (AppContext.sslLock) {
            onHttpsNoCertficates();
        }
    }


    private void onHttpsNoCertficates() {
        try {
            mBuilder.sslSocketFactory(HttpHelper.getSSLSocketFactory()).hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void onHttpCertficates() {
        int[] certficates = new int[]{};
        mBuilder.socketFactory(HttpHelper.getSSLSocketFactory(AppContext.context(), certficates));

        String[] host = new String[]{};
        mBuilder.hostnameVerifier(HttpHelper.getHostnameVerifier(host));


    }


    public OkHttpClient getOkHttpClient(boolean hasToken) {
        if (hasToken) {
            okHttpClient = mBuilder.addInterceptor(HttpHelper.getAuthorization()).build();
        } else {
            okHttpClient = mBuilder.build();
        }
        return okHttpClient;
    }
}